package cn.ii8080.i8.web;

import cn.ii8080.i8.web.annotaions.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

/**
 * api扫描
 */
@Component
@ConditionalOnProperty(prefix = "i8.api", name = "enabled", havingValue = "true")
public class RegisterApiRunner implements ApplicationRunner {
    @Autowired
    RequestMappingHandlerMapping mapping;
    @Autowired // 注入到容器中
    private Environment env;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
        List<ApiVo> apiVoList = new ArrayList<>();
        handlerMethods.forEach((r, method) -> {
            Api api = method.getMethodAnnotation(Api.class);
            if (api != null) {
                ApiVo apiVo = new ApiVo();
                apiVo.setName(api.value());
                apiVo.setPermissionsLogical(api.permissionsLogical());
                apiVo.setRolesLogical(api.rolesLogical());
                apiVo.setEnabled(api.enabled());
                apiVo.setRoles(new HashSet<>(Arrays.asList(api.roles())));
                apiVo.setPermissions(new HashSet<>(Arrays.asList(api.permissions())));
                Set<String> ms = new HashSet<>();
                Set<RequestMethod> methods = r.getMethodsCondition().getMethods();
                methods.forEach(rm -> {
                    ms.add(rm.name());
                });
                apiVo.setMethods(ms);
                Set<String> ps = new HashSet<>();
                Set<String> patterns = r.getPatternsCondition().getPatterns();
                patterns.forEach(s -> {
                    ps.add(s.replaceAll("\\{.\\}", "*"));
                });
                apiVo.setUrls(ps);
                apiVoList.add(apiVo);
            }
        });
        String server = env.getProperty("i8.api.server");
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.postForEntity(server, apiVoList, ApiVo.class);
    }
}
